import { localBaseUrl, serveBaseUrl } from './environment'
var axios = require('axios')
var qs = require('qs')

// 请求封装
function commonAxios(
  method,
  headers,
  baseUrl,
  url,
  params = {},
  success,
  failure
) {
  let parameters = ''
  if (method === 'GET' || method === 'DELETE' || method === 'POSTQUERY') {
    parameters = qs.stringify(params, {
      arrayFormat: 'indices',
      allowDots: true,
      encodeValuesOnly: true
    })
  } else {
    parameters = params
  }
  axios({
    method: method,
    url: url,
    params:
      method === 'GET' || method === 'DELETE' || method === 'POSTQUERY'
        ? params
        : null,
    data: method === 'POST' || method === 'PUT' ? parameters : null,
    withCredentials: false,
    baseURL: baseUrl,
    headers: headers
  })
    .then((res) => {
      if (res.data == '') {
        success(res)
      }
      if (success) {
        success(res.data)
      } else {
        failure(res.data)
      }
    })
    .catch((err) => {
      console.log('api error,HTTP CODE:' + err)
    })
}

//本地资源请求
function localAxios(
  method,
  localBaseUrl,
  url,
  params = {},
  success,
  failure,
  isAuthorization
) {
  let headers = {
    'Content-Type': 'application/json'
    // Authorization: store.state.token
  }
  return new Promise(() => {
    commonAxios(method, headers, localBaseUrl, url, params, success, failure)
  })
}
// 服务器资源请求
function serveAxios(
  method,
  serveBaseUrl,
  url,
  params = {},
  success,
  failure,
  isAuthorization
) {
  let headers = {
    'Content-Type': 'application/json'
    // Authorization: store.state.token
  }
  return new Promise(() => {
    commonAxios(method, headers, serveBaseUrl, url, params, success, failure)
  })
}

// 返回调用模板
export default {
  // 服务器get请求
  get(url, params, success, failure, isAuthorization) {
    return serveAxios(
      'GET',
      serveBaseUrl,
      url,
      params,
      success,
      failure,
      isAuthorization
    )
  },
  // 服务器post请求
  post(url, params, success, failure, isAuthorization) {
    return serveAxios(
      'POST',
      serveBaseUrl,
      url,
      params,
      success,
      failure,
      isAuthorization
    )
  },

  // 本地get请求
  get_local(url, params, success, failure, isAuthorization) {
    return localAxios(
      'GET',
      localBaseUrl,
      url,
      params,
      success,
      failure,
      isAuthorization
    )
  },
  // 本地post请求
  post_local(url, params, success, failure, isAuthorization) {
    return localAxios(
      'POST',
      localBaseUrl,
      url,
      params,
      success,
      failure,
      isAuthorization
    )
  }
}
